package com.example.designhbwxz.book.service.impl;

import com.example.designhbwxz.book.pojo.UserInfo;
import com.example.designhbwxz.book.repo.UserRepository;
import com.example.designhbwxz.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 用户业务层实现类
 *
 * @author shenzw
 * @date 2023/10/23
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 用户登陆
     *
     * @param account  账号
     * @param password 密码
     * @return String
     */
    @Override
    public String login(String account, String password) {
        UserInfo userInfo = userRepository.findByUserNameAndUserPassword(account, password);
        // 匹配账号和密码失败，则返回错误信息
        if (userInfo == null) {
            return "account / password ERROR！";
        }
        return "login success！";
    }

    /**
     * 注册用户
     *
     * @param userInfo 注册用户信息
     * @return String
     */
    @Override
    public String register(UserInfo userInfo) {
        if (checkUserExists(userInfo.getUserName())) {
            return "user already registered！";
        }
        userInfo.setCreateDate(new Date());
        userRepository.save(userInfo);

        return "registered success！";
    }

    /**
     * 校验账号是否已经存在，即注册过
     *
     * @param userName 账号
     * @return boolean
     */
    @Override
    public boolean checkUserExists(String userName) {
        UserInfo byUserName = userRepository.findByUserName(userName);
        return byUserName != null;
    }
}
